package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.entity.pojo.LfRole;
import com.entity.pojo.LfUser;
import com.mapper.LfRoleMapper;
import com.mapper.LfUserMapper;
import com.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author qiuchi
 */
@Service("userService")
@Log4j2
public class UserServiceImp implements UserService {

    @Resource
    private LfUserMapper userMapper;

    @Resource
    LfRoleMapper roleMapper;

    @Override
    public String getRole(String username) {
        Integer roleId = userMapper.selectOne(new QueryWrapper<LfUser>().eq("username", username)).getRoleId();
        return roleMapper.selectOne(new QueryWrapper<LfRole>().eq("id", roleId)).getRoleName();
    }

    @Override
    public Boolean userLogin(LfUser lfUser) {
        LfUser user = userMapper.selectOne(new QueryWrapper<LfUser>().eq("username", lfUser.getUsername()).eq("user_password", lfUser.getUserPassword()));
        return user != null;
    }

    @Override
    public List<LfUser> listUser() {
        return userMapper.selectList(new QueryWrapper<LfUser>().eq("deleted", 0));
    }

    @Override
    public int updateUser(LfUser user) {
        if (user.getId() != null) {
            if (userMapper.selectOne(new QueryWrapper<LfUser>().eq("username", user.getUsername()).ne("id", user.getId())) != null)
            {
                return -1;
            }
            return userMapper.updateById(user.setUpdateTime(LocalDateTime.now()).setRoleId(1));
        } else {
            if (userMapper.selectOne(new QueryWrapper<LfUser>().eq("username", user.getUsername())) != null) {
                return -1;
            }
            return userMapper.insert(user.setCreateTime(LocalDateTime.now()).setUserPassword("123456").setRoleId(2));
        }
    }

    @Override
    public int deleteUser(Integer id) {
        return userMapper.updateById(new LfUser().setDeleted(1).setId(id).setUpdateTime(LocalDateTime.now()));
    }

    @Override
    public LfUser getUser(String username) {
        return userMapper.selectOne(new QueryWrapper<LfUser>().eq("username", username));
    }
}
